def count_heading_level(line):
    """统计开头 # 的数量"""
    stripped = line.lstrip()
    return len(stripped) - len(stripped.lstrip('#'))

def reduce_one_heading_hash(line):
    """将 Markdown 标题的 # 减少一个"""
    stripped = line.lstrip()
    level = count_heading_level(stripped)
    new_level = max(1, level - 1)
    content = stripped[level:].strip()
    return f"{'#' * new_level} {content}\n"

def read_first_line(md_path):
    with open(md_path, 'r', encoding='utf-8') as f:
        first_line = f.readline()
    if count_heading_level(first_line) <= 1:
        return "全部返回"
    # 否则开始处理所有行
    modified_lines = []
    with open(md_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped = line.lstrip()
            if stripped.startswith('#'):
                modified_lines.append(reduce_one_heading_hash(line))
            else:
                modified_lines.append(line)
    # 写入修改后的内容
    with open(md_path, 'w', encoding='utf-8') as f:
        f.writelines(modified_lines)
    # 读取修改后的内容并返回
    with open(md_path, 'r', encoding='utf-8') as f:
        return f.read()

def get_first_heading_hash_count(lines):
    for line in lines:
        stripped = line.lstrip()
        if stripped.startswith('#'):
            count = 0
            for char in stripped:
                if char == '#':
                    count += 1
                else:
                    break
            return count
    return 0  # 如果没有标题行


# 示例用法
md_file = "D:\\hbyt\\AI智能投标\\能力组件-附件\\测试1.md"

lines = read_first_line(md_file)
if get_first_heading_hash_count(lines)==1:
    print("层级达到最低")
else:
    lines = read_first_line(md_file)

print(lines)